package com.sskj.mqtt.many;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: Like
 * @Date: 2025/3/3 15:40
 * @Description: mqtt客户端map 存储客户端对应的消息处理器
 */
public class MqttClientMap {

    /**
     * 存储处理器的映射关系，使用clientId作为键，值为一个列表，列表中的每个元素都是一个HandlerEntry对象，
     */
    private static final Map<String, List<HandlerEntry>> handlers = new ConcurrentHashMap<>();

    /**
     * 注册处理器
     *
     * @param clientId
     * @param topicFilter
     * @param wrapper
     */
    public static void registerHandler(String clientId, String topicFilter, HandlerWrapper wrapper) {
        TopicPattern pattern = new TopicPattern(topicFilter);
        handlers.computeIfAbsent(clientId, k -> new CopyOnWriteArrayList<>())
                .add(new HandlerEntry(pattern, wrapper, topicFilter)); // 传递原始表达式
    }

    /**
     * 根据clientId和实际topic获取对应的处理器
     *
     * @param clientId
     * @param actualTopic
     * @return
     */
    public static HandlerWrapper getHandler(String clientId, String actualTopic) {
        return handlers.getOrDefault(clientId, Collections.emptyList())
                .stream()
                .filter(entry -> entry.pattern.matches(actualTopic))
                .findFirst()
                .map(entry -> entry.wrapper)
                .orElse(null);
    }

    /**
     * 存储处理器的包装类，包括匹配模式、处理器和原始过滤表达式
     */
    private static class HandlerEntry {
        final TopicPattern pattern;
        final HandlerWrapper wrapper;
        final String originalFilter; // 新增原始过滤表达式存储

        HandlerEntry(TopicPattern pattern, HandlerWrapper wrapper, String originalFilter) {
            this.pattern = pattern;
            this.wrapper = wrapper;
            this.originalFilter = originalFilter;
        }
    }

    /**
     * 根据clientId获取订阅的topic
     *
     * @param clientId
     * @return
     */
    public static String[] getTopicsByClientId(String clientId) {
        return handlers.getOrDefault(clientId, Collections.emptyList())
                .stream()
                .map(entry -> entry.originalFilter)
                .distinct() // 去重（可选）
                .toArray(String[]::new);
    }


}

